import React, { useState, useCallback, useContext, useRef, Ref } from 'react';
import { AutoComplete, Button, Empty, Form, Input, Space } from 'antd';
import {
  SearchOutlined,
  TableOutlined,
  PlusOutlined,
  ReloadOutlined,
} from '@ant-design/icons';
import cls from 'classnames';
import { departmentAPI } from '@/pages/SystemController/DepartmentController/type';
import ChangeColumns from '@/components/ActionButton/components/ChangeColumns';
import { DeptContext } from '../hooks';
import { IOneModalRef } from '@/pages/type';
import { TypographyTitle } from '@/components/Typography';

export const SearchBox = React.forwardRef(
  (
    {
      onReload,
      changeColumns,
      showColumns,
      onSearch,
      dataList,
      getNewKey,
      addOrEditModal,
    }: departmentAPI.ISearchBox,
    ref: any,
  ) => {
    const [form] = Form.useForm();
    const [visible, setVisible] = React.useState(false);
    const [options, setOptions] = useState<any>([]);

    const { curRes } = useContext(DeptContext); //拿到权限

    let clsName = 'depart-layout-search';

    let treeListArr: any = dataList(); //平铺的树数据

    const changeColRef: Ref<IOneModalRef> = useRef(null); //弹框的ref

    React.useImperativeHandle(ref, () => ({
      getSearchValue: () => {
        let searchValue = form?.getFieldsValue();
        return searchValue;
      },
    }));

    // 处理输入搜索值数据
    const loopArray = (array: any[]): Record<string, any>[] => {
      const tileArray: Record<string, any>[] = [];
      const loop = (data: any[]) => {
        data?.forEach((item) => {
          if (item?.children) {
            loop(item?.children);
          }
          tileArray.push(item);
        });
      };
      loop(array);
      return tileArray;
    };

    // 确认修改显示列
    const onOK = (columns: any[]) => {
      if (columns) {
        changeColumns(columns);
        changeColRef?.current?.onModalCancel();
      }
    };

    // 关闭显示列
    const onClose = () => {
      setVisible(false);
    };

    // 打开显示列
    const onOpen = () => {
      setVisible(true);
    };

    // 搜索框展开 数据处理
    const onSearchValueChanage = useCallback(
      (e: React.ChangeEvent<HTMLInputElement>) => {
        const searchValue = e.target.value;
        const tileArray: Record<string, any>[] = loopArray(treeListArr);

        if (searchValue && searchValue.length > 0) {
          const newOption: any[] = tileArray
            ?.map((item) => {
              if (item?.name?.includes(searchValue)) {
                // const name = item?.name;
                // const nameLength = name?.length;
                // const select = name?.search(searchValue);
                // const searchLength = searchValue?.length;
                // const afterStr = name?.slice(0, select);
                // const selectStr = searchValue;
                // const beforeStr = name?.slice(
                //   select + searchLength,
                //   nameLength,
                // );

                return {
                  value: item?.name,
                  key: item?.id,
                  // label: (
                  //   <div>
                  //     <span>{afterStr}</span>
                  //     <span style={{ color: 'red' }}>{selectStr}</span>
                  //     <span>{beforeStr}</span>
                  //   </div>
                  // ),
                };
              }
            })
            ?.filter((item) => typeof item !== 'undefined');
          setOptions(newOption);
        } else {
          setOptions([]);
        }
      },
      [treeListArr, options],
    );

    // 点击搜索
    const searchSelect = (value: any, options: any) => {
      let searchValues = form.getFieldsValue();
      onSearch(searchValues);
      if (options && options?.key) {
        setTimeout(() => {
          scrollToAnchor(options?.key);
        }, 1000);

        // 传入搜索节点的key值
        getNewKey(options?.key);
      }
    };

    // 滚动定位
    const scrollToAnchor = (id: string) => {
      let anchorElement = document.getElementById(id);
      if (id) {
        anchorElement?.scrollIntoView({ block: 'start', behavior: 'smooth' });
      }
    };

    return (
      <>
        <TypographyTitle
          level={4}
          style={{
            margin: 0,
          }}
        >
          组织管理
        </TypographyTitle>
        <Space>
          <Form
            form={form}
            style={{ position: 'relative' }}
            className={cls(`${clsName}-form`)}
            onValuesChange={(changedValues, allValues) => {
              if (!changedValues?.name) {
                onReload();
              }
            }}
          >
            <Form.Item name="name">
              <AutoComplete
                onSelect={searchSelect}
                options={options}
                notFoundContent={<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
                style={{ width: 400 }}
              >
                <Input
                  suffix={<SearchOutlined />}
                  onChange={onSearchValueChanage}
                  placeholder="请按机构名称搜索"
                  allowClear={true}
                  addonAfter={
                    <span onClick={onReload}>
                      <ReloadOutlined />
                    </span>
                  }
                />
              </AutoComplete>
            </Form.Item>
          </Form>
          {/* <Button
        type={'primary'}
        className={cls(`${clsName}-btn`)}
        icon={<SearchOutlined />}
        onClick={onFormSearch}
      >
        查询
      </Button> */}
          {/* <Button
        className={cls(`${clsName}-btn`)}
        icon={<ReloadOutlined />}
        onClick={onReload}
      >
        重置
      </Button> */}
          {curRes['/departmentController/add'] && (
            <Button
              // className={cls(`${clsName}-btn`)}
              icon={<PlusOutlined />}
              type={'primary'}
              onClick={() => {
                addOrEditModal(false, {});
              }}
            >
              添加
            </Button>
          )}
          {/* <Button
            // className={cls(`${clsName}-btn`)}
            icon={<ReloadOutlined />}
            onClick={onReload}
          >
            重置
          </Button> */}
          <Button icon={<TableOutlined />} onClick={onOpen}>
            显示列
          </Button>
        </Space>

        {visible && (
          <ChangeColumns
            onClose={onClose}
            onOk={onOK}
            columnsList={showColumns}
            ref={changeColRef}
          />
        )}
      </>
    );
  },
);
